package com.ruoyi.system.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.ProjectConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtil;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.system.domain.AppBanner;
import com.ruoyi.system.domain.AppVersion;
import com.ruoyi.system.domain.DivineCase;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.domain.Report;
import com.ruoyi.system.domain.ReportSetting;
import com.ruoyi.system.domain.SystemExplain;
import com.ruoyi.system.domain.UserFeedback;
import com.ruoyi.system.domain.UserNotice;
import com.ruoyi.system.mapper.AppBannerMapper;
import com.ruoyi.system.mapper.AppVersionMapper;
import com.ruoyi.system.mapper.DivineCaseMapper;
import com.ruoyi.system.mapper.PriceSettingMapper;
import com.ruoyi.system.mapper.ReportMapper;
import com.ruoyi.system.mapper.ReportSettingMapper;
import com.ruoyi.system.mapper.SystemExplainMapper;
import com.ruoyi.system.mapper.TaskRewardSetMapper;
import com.ruoyi.system.mapper.UserFeedbackMapper;
import com.ruoyi.system.mapper.UserNoticeMapper;
import com.ruoyi.system.pojo.AppCustomerVo;
import com.ruoyi.system.pojo.AppTaskRewardDTO;
import com.ruoyi.system.service.AppSystemService;
import com.ruoyi.system.service.ISmsRecordService;
import com.ruoyi.user.domain.CustomerConfig;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.UserAccountManage;
import com.ruoyi.user.domain.UserExtend;
import com.ruoyi.user.domain.UserPurposeSet;
import com.ruoyi.user.domain.UserThirdParty;
import com.ruoyi.user.mapper.CustomerConfigMapper;
import com.ruoyi.user.mapper.UserAccountManageMapper;
import com.ruoyi.user.mapper.UserExtendMapper;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.mapper.UserPurposeSetMapper;
import com.ruoyi.user.mapper.UserThirdPartyMapper;
import com.ruoyi.user.pojo.AppAccountManageVO;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class AppSystemServiceImpl implements AppSystemService {

	@Autowired
	private UserPurposeSetMapper userPurposeSetMapper;
	@Autowired
	private PriceSettingMapper priceSettingMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ISmsRecordService smsRecordService;
	@Autowired
	private TaskRewardSetMapper taskRewardSetMapper;
	@Autowired
	private UserNoticeMapper userNoticeMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserThirdPartyMapper userThirdPartyMapper;
	@Autowired
	private UserFeedbackMapper userFeedbackMapper;
	@Autowired
	private ReportSettingMapper reportSettingMapper;
	@Autowired
	private ReportMapper reportMapper;
	@Autowired
	private DivineCaseMapper divineCaseMapper;
	@Autowired
	private SystemExplainMapper systemExplainMapper;
	@Autowired
	private AppBannerMapper bannerMapper;
	@Autowired
	private AppVersionMapper appVersionMapper;
	@Autowired
	private UserAccountManageMapper userAccountManageMapper;
	@Autowired
	private CustomerConfigMapper customerConfigMapper;
	@Autowired
	private UserExtendMapper userExtendMapper;
	
	@Override
	public AjaxResult sendMobileCode(String mobile, Integer type) {
		AjaxResult ajaxResult = smsRecordService.sendSms(type, mobile);
		return ajaxResult;
	}
	
	/**
	 * 	获取用户ID
	 * @return
	 */
	private Long getLoginUserId() {
		Object object = RequestContext.get("userInfo");
		if(null == object) {
			return null;
		}
		JWTUser jwtUser = (JWTUser) object;
		if(null == jwtUser || null == jwtUser.getId()) {
			return null;
		}
		return jwtUser.getId();
	}
	
	@Override
	public AjaxResult qryUserPurposeList() {
		List<UserPurposeSet> list = userPurposeSetMapper.selectList(new LambdaQueryWrapper<UserPurposeSet>().orderByAsc(UserPurposeSet::getSort));
		return AjaxResult.success(CollectionUtil.isEmpty(list)?new ArrayList<UserPurposeSet>():list);
	}

	@Override
	public AjaxResult parameterList(Integer type, Integer parentId, HttpServletRequest request) {
		try {
			// 0=苹果 1=安卓
			int amountType = 1;
			String clientType = request.getHeader("clientType");
			if(StringUtils.isNotEmpty(clientType)) {
				if(clientType.equalsIgnoreCase("iOS")) {
					amountType = 0;
				}
			}
			Map<String,Object> map = new HashMap<String,Object>();
			switch (type) {
			case 1://余额充值规格
				List<PriceSetting> priceSetting = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "余额")
						.eq(PriceSetting::getAmountType, amountType).eq(PriceSetting::getEnabled, 1).orderByDesc(PriceSetting::getSort));
				priceSetting.parallelStream().forEach(dl ->{
					dl.setCurrentPrice(new BigDecimal(dl.getCurrentPrice().stripTrailingZeros().toPlainString()));
					dl.setOriginalPrice(new BigDecimal(dl.getOriginalPrice().stripTrailingZeros().toPlainString()));
				});
				map.put("currencyList",priceSetting);
				break;
			case 2://VIP
				Long loginUserId = getLoginUserId();
				if(null == loginUserId) {
					return AjaxResult.error(50010,"请重新登录");
				}
				priceSetting = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "VIP充值")
						.eq(PriceSetting::getAmountType, amountType).eq(PriceSetting::getEnabled, 1).orderByDesc(PriceSetting::getSort));
				priceSetting.parallelStream().forEach(dl ->{
					dl.setCurrentPrice(new BigDecimal(dl.getCurrentPrice().stripTrailingZeros().toPlainString()));
					dl.setOriginalPrice(new BigDecimal(dl.getOriginalPrice().stripTrailingZeros().toPlainString()));
				});
				map.put("vipList",priceSetting);
				// 查询是否VIP
				User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getVip,User::getVipExpireTime
						,User::getVipLevel));
				if(null == user) {return AjaxResult.error(50010,"请重新登录");}
				String vipTime = "暂未开通VIP";
				if(user.getVip() > 0 && DateUtils.isOverdue(new Date(), user.getVipExpireTime())) {
					vipTime = DateUtils.dateToString(user.getVipExpireTime(), "yyyy.MM.dd HH:mm");
					map.put("vipLevel",user.getVipLevel());
				}
				map.put("vipTime",vipTime);
				break;
			case 3:// 提现比例
				map.put("ratioShow","10%");
				map.put("ratio","0.1");
				PriceSetting one = priceSettingMapper.selectOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "提现比例")
						.eq(PriceSetting::getEnabled, 1));
				if(null != one) {
					map.put("ratioShow",one.getPriceName());
					map.put("ratio",new BigDecimal(one.getCurrentPrice().stripTrailingZeros().toPlainString()));
				}
				break;
			case 4:// 动态banner
				List<AppBanner> bannerList = bannerMapper.selectList(new LambdaQueryWrapper<AppBanner>().eq(AppBanner::getType, 1).eq(AppBanner::getIsDelete, 0));
				map.put("bannerList",bannerList);
				break;
				
			case 5: // 礼物列表
				List<PriceSetting> giftList = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "gift").eq(PriceSetting::getEnabled, 1));
				map.put("giftList",giftList);
				break;
			case 6: // 约玩类型列表
				List<PriceSetting> playList = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "约玩类型").eq(PriceSetting::getEnabled, 1));
				map.put("playList",playList);
				break;
			case 7: // 话题列表
				List<PriceSetting> talkList = priceSettingMapper.selectList(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "话题").eq(PriceSetting::getEnabled, 1));
				map.put("talkList",talkList);
				break;
			case 8:// 消息banner
				bannerList = bannerMapper.selectList(new LambdaQueryWrapper<AppBanner>().eq(AppBanner::getType, 2).eq(AppBanner::getIsDelete, 0));
				map.put("bannerList",bannerList);
				break;
			default:
				break;
			}
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
		
	}

	@Override
	public AjaxResult getUserTaskRewardList(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String, Object>();
			String taskTime = DateUtils.format(new Date(), "yyyyMMdd");
			Integer type = 1;	// 1=今日2=本月
			List<AppTaskRewardDTO> list = taskRewardSetMapper.getUserTaskRewardList(taskTime, loginUserId, type);
			list.parallelStream().forEach(reward ->{
				// 点赞男用户动态  taskCount
				reward.setTitle(reward.getTitle()+reward.getProgressCount()+"/"+reward.getTaskCount()+"次");
			});
			//String totalAmount = userTotalCapitalMapper.getAmountByUserId(3, loginUserId);
			map.put("totalAmount","0");
			map.put("list", list);
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getPrivacySet(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getSecrecy,User::getHideView));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("secrecy", user.getSecrecy());
			map.put("hideView", user.getHideView());
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult updatePrivacySet(Integer type, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getSecrecy,User::getHideView));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(1 == type) {// 距离
				user.setSecrecy(user.getSecrecy() == 1 ? 0 : 1);
				
			}else if(2 == type) {//	隐身访问
				user.setHideView(user.getHideView() == 1 ? 0 : 1);
			}
			userMapper.updateById(user);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getNoticeSet(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserNotice userNotice = userNoticeMapper.selectOne(new LambdaQueryWrapper<UserNotice>().eq(UserNotice::getUserId, loginUserId));
			if(null == userNotice) {
				userNotice = new UserNotice();
				userNotice.setUserId(loginUserId);
				userNotice.setIsOnline(1);
				userNotice.setIsDynamic(1);
				userNotice.setIsFans(1);
				userNotice.setIsLook(1);
				userNotice.setIsInvite(1);
				userNotice.setIsInteract(1);
				userNoticeMapper.insert(userNotice);
			}
			return AjaxResult.success(userNotice);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult updateNoticeSet(Integer type, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			UserNotice userNotice = userNoticeMapper.selectOne(new LambdaQueryWrapper<UserNotice>().eq(UserNotice::getUserId, loginUserId));
			if(null == userNotice) {
				userNotice = new UserNotice();
				userNotice.setUserId(loginUserId);
				userNotice.setIsOnline(1);
				userNotice.setIsDynamic(1);
				userNotice.setIsFans(1);
				userNotice.setIsLook(1);
				userNotice.setIsInteract(1);
				userNotice.setIsInvite(1);
				userNoticeMapper.insert(userNotice);
			}
			// 1=关注上线通知 2=关注用户发布动态 3=新增粉丝 4=TA看过我 5=互动奖励 6=邀请好友
			switch (type) {
			case 1:
				userNotice.setIsOnline(userNotice.getIsOnline() == 1 ? 0 : 1);
				break;
			case 2:
				userNotice.setIsDynamic(userNotice.getIsDynamic() == 1 ? 0 : 1);
				break;
			case 3:
				userNotice.setIsFans(userNotice.getIsFans() == 1 ? 0 : 1);
				break;
			case 4:
				userNotice.setIsLook(userNotice.getIsLook() == 1 ? 0 : 1);
				break;
			case 5:
				userNotice.setIsInteract(userNotice.getIsInteract() == 1 ? 0 : 1);
				break;
			case 6:
				userNotice.setIsInvite(userNotice.getIsInvite() == 1 ? 0 : 1);
				break;
			default:
				break;
			}
			userNoticeMapper.updateById(userNotice);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult updatePhone(String mobile, String mobileCode, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getPhone));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			
			Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getPhone, mobile));
			if(null != count && count > 0) {
				return AjaxResult.error("手机号码已经存在");
			}
			boolean right = false;
			Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix() +"_"+ 3 + "_" + mobileCode);
			if (savedMobile != null && mobile.equals(savedMobile.toString())) {
				right = true;
			}
			if("518186".equals(mobileCode)){
				right = true;
			}
			if (!right) {
				return AjaxResult.error("验证码不一致");
			}
			user.setUpdatePhone("用户主动修改手机号码,旧号码为："+user.getPhone()+"-新号码为："+mobile+"，修改日期："+new Date());
			user.setPhone(mobile);
			userMapper.updateById(user);
			//查询是否绑定微信
			UserThirdParty one = userThirdPartyMapper.selectOne(new LambdaQueryWrapper<UserThirdParty>().eq(UserThirdParty::getUserId, loginUserId));
			if(null != one) {
				one.setMobile(mobile);
				userThirdPartyMapper.updateById(one);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult submitFeedback(UserFeedback userFeedback, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			userFeedback.setUserId(loginUserId);
			userFeedbackMapper.insert(userFeedback);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getHelpCenter(HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getNotice,User::getOrderMsg));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("notice", user.getNotice());	// 消息通知
			map.put("orderMsg", user.getOrderMsg());// 抢单池通知
			map.put("userAgreement", "https://www.baidu.com");// 用户协议
			map.put("privacyAgreement", "https://www.baidu.com");// 隐私协议
			map.put("aboutUs", "https://www.baidu.com");// 关于我们
			return AjaxResult.success(map);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult setMsgNotice(Integer type, HttpServletRequest request) {
		try {
			Long loginUserId = getLoginUserId();
			if(null == loginUserId) {
				return AjaxResult.error(50010,"请重新登录");
			}
			User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getNotice,User::getOrderMsg));
			if(null == user) {
				return AjaxResult.error(50010,"请重新登录");
			}
			if(1 == type) {
				user.setNotice(user.getNotice()==1?0:1);
			}else {
				user.setOrderMsg(user.getOrderMsg()==1?0:1);
			}
			userMapper.updateById(user);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getReportSetting(HttpServletRequest request) {
		return AjaxResult.success(reportSettingMapper.selectList(new LambdaQueryWrapper<ReportSetting>().eq(ReportSetting::getEnabled, 1)));
	}

	@Override
	public AjaxResult reportUser(Report report, HttpServletRequest request) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(loginUserId.longValue() == report.getReportedUserId().longValue()) {
			return AjaxResult.error("自己不可举报自己");
		}
		report.setReportUserId(loginUserId);
		report.setCreateTime(new Date());
		report.setReportTime(new Date());
		reportMapper.insert(report);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult getDivineCase(Integer type) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		List<DivineCase> list = divineCaseMapper.selectList(new LambdaQueryWrapper<DivineCase>().eq(DivineCase::getType, type));
		return AjaxResult.success(list);
	}

	@Override
	public AjaxResult getExplain(Integer type) {
		List<SystemExplain> selectList = systemExplainMapper.selectList(new LambdaQueryWrapper<SystemExplain>().eq(SystemExplain::getType, type));
		return AjaxResult.success(selectList);
	}

	@Override
	public AjaxResult appVersion(HttpServletRequest request) {
		try {
			String clientType = request.getHeader("clientType");
			if(StringUtils.isEmpty(clientType)) {
				return AjaxResult.error("手机型号暂不支持");
			}
			List<AppVersion> list = appVersionMapper.selectList(new LambdaQueryWrapper<AppVersion>().eq(AppVersion::getClientType, clientType).orderByDesc(AppVersion::getCreateTime).last("limit 1"));
			AppVersion version = null;
			if(CollectionUtil.isNotEmpty(list)) {
				version = list.get(0);
			}
			return AjaxResult.success(version==null?new AppVersion():version);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult getAccountManage() {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		// 父级 = 152
		// 子集 156、 158
		Long masterUserId = loginUserId;
		Integer count = userAccountManageMapper.selectCount(new LambdaQueryWrapper<UserAccountManage>().eq(UserAccountManage::getUserId, loginUserId));
		List<AppAccountManageVO> accountManage = new ArrayList<AppAccountManageVO>();
		if(count > 0) { // 是主账号
			accountManage = userAccountManageMapper.getAccountManage(loginUserId,0);
		}else {
			UserAccountManage account = userAccountManageMapper.selectOne(new LambdaQueryWrapper<UserAccountManage>().eq(UserAccountManage::getAccountId, loginUserId));
			if(null != account) {
				masterUserId = account.getUserId();
				accountManage = userAccountManageMapper.getAccountManage(account.getUserId(),0);
			}
		}
		List<AppAccountManageVO> accountManage2 = userAccountManageMapper.getAccountManage(masterUserId,1);
		if(CollectionUtil.isNotEmpty(accountManage2)) {
			accountManage.add(accountManage2.get(0));
			for (AppAccountManageVO am : accountManage) {
				if(am.getUserId().longValue() == masterUserId.longValue()) {
					am.setIsMaster(1);
				}
			}
		}
		return AjaxResult.success(accountManage);
	}

	private String exampleCode = "518186";
	
	@Override
	public AjaxResult addAccountManage(String mobile, String mobileCode) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		boolean right = false;
		Object savedMobile = redisUtil.get(ProjectConstant.RedisKey.MOBILE_CODE.getKeyPrefix() +"_"+ 6 + "_" + mobileCode);
		if (savedMobile != null && mobile.equals(savedMobile.toString())) {
			right = true;
		}
		if(exampleCode.equals(mobileCode)){
			right = true;
		}
		if (!right) {
			return AjaxResult.error("验证码不一致");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,mobile)
				.select(User::getId,User::getPhone));
		if(null == user) {
			return AjaxResult.error("该手机号码未注册");
		}
		UserAccountManage userAccountManage = userAccountManageMapper.selectOne(new LambdaQueryWrapper<UserAccountManage>().eq(UserAccountManage::getUserId, loginUserId)
				.eq(UserAccountManage::getAccountId, user.getId()));
		if(null != userAccountManage) {
			return AjaxResult.error("该用户已绑定");
		}
		userAccountManage = new UserAccountManage();
		userAccountManage.setUserId(loginUserId);
		userAccountManage.setAccountId(user.getId());
		userAccountManage.setIsUnreadMsg(0);
		userAccountManage.setCreateTime(new Date());
		userAccountManageMapper.insert(userAccountManage);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult delAccountManage(Long id) {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		userAccountManageMapper.deleteById(id);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult msgReadNotice() {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		LambdaUpdateWrapper<UserAccountManage> update = new LambdaUpdateWrapper<UserAccountManage>();
		update.eq(UserAccountManage::getAccountId, loginUserId);
		UserAccountManage userAccountManage = new UserAccountManage();
		userAccountManage.setIsUnreadMsg(0);
		userAccountManageMapper.update(userAccountManage, update);
		return AjaxResult.success();
	}

	@Override
	public void setReadMsg(Long userId) {
		LambdaUpdateWrapper<UserAccountManage> update = new LambdaUpdateWrapper<UserAccountManage>();
		update.eq(UserAccountManage::getAccountId, userId);
		UserAccountManage userAccountManage = new UserAccountManage();
		userAccountManage.setIsUnreadMsg(1);
		userAccountManageMapper.update(userAccountManage, update);
	}

	@Override
	public AjaxResult isUnreadMsg() {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		
		if(redisUtil.sHasKey(ProjectConstant.REDIS_MSG_PREFIX, loginUserId)) {
			return AjaxResult.success("成功",1);
		}else {
			return AjaxResult.success("成功",0);
		}
	}

	@Override
	public AjaxResult cleanUnreadMsg() {
		Long loginUserId = getLoginUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		redisUtil.setRemove(ProjectConstant.REDIS_MSG_PREFIX, loginUserId);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult getCustomerInfo() {
		CustomerConfig config = customerConfigMapper.selectOne(new QueryWrapper<CustomerConfig>().orderByDesc("create_time").last("limit 1"));
		if(null == config) {
			return AjaxResult.error("当前暂无客服");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, config.getUserId())
				.select(User::getId,User::getNickName,User::getHeadPic));
		if(null == user) {
			return AjaxResult.error("当前暂无客服");
		}
		UserExtend extend = userExtendMapper.selectOne(new LambdaQueryWrapper<UserExtend>().eq(UserExtend::getUserId, user.getId()));
		if(null == extend || StringUtils.isEmpty(extend.getEmUsername())) {
			return AjaxResult.error("当前暂无客服");
		}
		AppCustomerVo custome = new AppCustomerVo();
		custome.setUserId(config.getUserId());
		custome.setNickName(user.getNickName());
		custome.setHeadPic(user.getHeadPic());
		custome.setEmUsername(extend.getEmUsername());
		custome.setContent(config.getContent());
		// 判断是否在上班时间内
		int week = DateUtil.getWeekOfDateChineseInteger();
		if(!config.getWeek().contains(String.valueOf(week))) {
			// 非上班时间
			custome.setIsWork(0);
		}else {
			// 在上班时间内 判断时间
			String pattern = "HH:mm";
			String now = DateUtils.dateToString(new Date(), pattern);
			if(!DateUtils.isEffectiveDate(DateUtils.stringToDate(now, pattern), DateUtils.stringToDate(config.getBegTime(), pattern), 
					DateUtils.stringToDate(config.getEndTime(), pattern))) {
				// 非上班时间
				custome.setIsWork(0);
			}
		}
		return AjaxResult.success(custome);
	}
}
